package com.pachong.android.framework.httprequest.responsecallbacks;

import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;

import com.pachong.android.framework.httprequest.HttpRequest;
import com.pachong.android.framework.httprequest.IResponseDataParser;
import com.pachong.android.framework.httprequest.ResponseParser;
import com.pachong.android.frameworkbase.dialog.ProgressFragment;
import com.pachong.android.frameworkbase.utils.SLog;

import org.json.JSONException;
import org.json.JSONObject;

/**
 * http 请求回调
 *
 * @Author: PV
 * @E-mail: pengveivei@sina.cn
 * @CreateDate: 2016/7/25 11:48
 * @Version: 1.0.0
 */
public abstract class DataRequestListener<T> extends RequestListener<T> {

    private static final String INTERNAL_SERVER_ERROR = "REST/INTERNAL_SERVER_ERROR";
    public static final int ERR_CODE_INVALID_NET = -1;//  网路异常，可能断开了or其他情况
    public static final int ERR_CODE_PARSE = -2;  // 解析异常， 服务器返回的数据非json格式
    public static final int ERR_CODE_INTERNAL_SERVER = -3;  // 数据异常：服务端返回具体的error msg，客户端自己判断给用户统一的展示

    private static final String ERR_STR_INVALID_NET = "网络不可用，请检查网络";
    private static final String ERR_STR_PARSE = "数据解析异常";

    ProgressFragment progressFragment;
    boolean isProgressEnable;


    private static final String ERR_STR_INTERNAL_SERVER = "未知错误";


    /**
     * 使用默认的解析器
     * @param clazz
     */
    public DataRequestListener(@NonNull Class clazz) {
        super(new ResponseParser<T>(clazz));
        enableProgress(true);
    }


    public DataRequestListener(@NonNull IResponseDataParser dataParser) {
        super(dataParser);
        enableProgress(true);
    }


    /**
     * Enable progress fragment when requesting http
     */
    public void enableProgress(boolean enableProgress) {
        if (isProgressEnable != enableProgress) {
            isProgressEnable = enableProgress;
        }
    }

    @Override
    public void onStart(Context context, String url) {
        if (context instanceof AppCompatActivity) {
            showProgress(context);

        } else {
            SLog.e(HttpRequest.TAG, "onStart(): 没有调用刷新dialog");
        }

    }

    @Override
    public void onSuccess(T t) {
        hideProgress();
    }

    @Override
    public void onFailure(Throwable t, int errorNo, String strMsg) {
        hideProgress();
    }

    /**
     * 显示加载对话框
     *
     * @param context
     */
    public void showProgress(Context context) {
        if (isProgressEnable) {
            AppCompatActivity act = (AppCompatActivity) context;
            if (progressFragment == null) {
                progressFragment = new ProgressFragment();
                progressFragment.show(act.getSupportFragmentManager());

            } else if (!progressFragment.isVisible()) {
                progressFragment.show(act.getSupportFragmentManager());
            }
        }
    }

    /**
     * 隐藏加载对话框
     */
    public void hideProgress() {
        if (isProgressEnable) {
            if (progressFragment != null && progressFragment.isVisible()) {
                progressFragment.dismissAllowingStateLoss();
            }
        }

    }

    @Override
    public void onDeliverFailureResponse(Throwable t, int errCode, String errStr) {
        String errMsg;

        // errCode == -1 值是从父类返回
        if (errCode == -1 && TextUtils.isEmpty(errStr)) {
            // 没有网络
            errMsg = ERR_STR_INVALID_NET;
            errCode = ERR_CODE_INVALID_NET;

        } else {
            // 解析从服务器返回的数据
            try {
                JSONObject jobj = new JSONObject(errStr);
                String code = jobj.optString("code");
                String message = jobj.optString("message");

                if (!TextUtils.isEmpty(code) && !TextUtils.isEmpty(message)) {
                    if (errCode == 400) {
                        errMsg = message;
                    } else if(errCode == 403) {
                        errMsg = "授权失败";
                    } else {
                        if (TextUtils.isEmpty(message)) {
                            message = ERR_STR_INTERNAL_SERVER;
                        }
                        errMsg = message;
                    }

                } else {
                    errMsg = ERR_STR_PARSE;
                    errCode = ERR_CODE_PARSE;
                    Log.w("Http", "解析异常， error code 或者 error message 为空");
                }

            } catch (JSONException e) {
                e.printStackTrace();
                // 解析异常， 服务器返回的数据非json格式
                errMsg = ERR_STR_PARSE;
                errCode = ERR_CODE_PARSE;
                Log.w("Http", "解析异常， 服务器返回的数据非json格式");
            }
        }

        onFailure(t, errCode, errMsg);
    }
}
